import { DownOutlined, EllipsisOutlined, CloseCircleOutlined } from '@ant-design/icons';
import {
  Button,
  Input,
  Modal,
  Form,
  Select,
  Popconfirm,
  Space,
  Layout,
  Avatar,
  Typography,
  Breadcrumb,
  Pagination,
  Dropdown,
  Menu,
  Checkbox,
  App,
} from 'antd';
import { debounce } from 'lodash';
import React, { useState, memo, useEffect, useCallback, useRef } from 'react';
import { useLocation } from 'react-router-dom';

import appService from '@/api/services/appService';
import { ExtensionInfo, ExtensionpageData } from '@/common/types';
import GradientBox from '@/components/GradientBox';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
// import EmptyPape from '@/components/empty/EmptyPage';
import NotData from '@/components/NotData';
import PagesHeader from '@/components/pages-header';
import TipDesc from '@/components/tipDesc/tipDesc';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { useRouter } from '@/router/hooks';
import { useManagePage } from '@/store/configStore';
import { useThemeToken } from '@/theme/hooks';

import BatchImportModal from './components/BatchImportModal';
import './extension.css';

import type { InputRef, PaginationProps } from 'antd';

interface Application {
  id: string;
  name: string;
  url: string;
  type: string;
  description: string;
}

interface ApplicationPageData {
  list: ExtensionInfo[];
  page: number;
  page_size: number;
  total: number;
}

interface ExtensionPageData {
  group_key: string;
  page_data: ApplicationPageData;
}

const { Header, Content } = Layout;
const { Title, Text } = Typography;

const iconList = [
  'bxs--receipt',
  'bxs--landmark',
  'bxs--building-house',
  'bxs--cabinet',
  'bxs--brain',
  'bxs--arch',
  'bxs--bookmark',
  'bxs--castle',
  'bxs--graduation',
  'bxs--school',
  'bxs--briefcase-alt-2',
  'bxs--bank',
  'bxs--smile',
  'bxs--florist',
  'basil--invoice-solid',
  'basil--lightbulb-alt-solid',
];

function getNextValidChar(str, index) {
  if (!str || typeof str !== 'string' || index >= str.length) {
    return undefined;
  }
  const char = str[index];
  // 包含中文字符的正则表达式
  const isChineseOrLetter = /^[\u4e00-\u9fa5a-zA-Z]+$/;
  if (isChineseOrLetter.test(char)) {
    return char;
  }
  return getNextValidChar(str, index + 1);
}

interface AppItemProps {
  app: Application;
  selectedAppIds: string[];
  onClick: () => void;
  isPc?: boolean;
  isEditMode: boolean;
  onCheck: (id: number, isChecked: boolean) => void;
}

const AppItem: React.FC<AppItemProps> = memo(
  ({ app, onClick, isEditMode, onCheck, selectedAppIds }) => {
    return (
      <GradientBox
        // onClick={() => handleSelected(addModel)}
        showCheck={false}
        key={app?.id}
        active={selectedAppIds.includes(app?.id)}
      >
        <div
          className="cursor-pointer transition-shadow hover:shadow-sm"
          style={{
            height: '78px',
            position: 'relative',
          }}
          onClick={onClick}
        >
          <Checkbox
            style={{ position: 'absolute', top: '6px', right: '8px' }}
            checked={selectedAppIds.includes(app?.id)}
            onClick={(e) => {
              e.stopPropagation();
            }}
            onChange={(e) => {
              onCheck(app?.id, e.target.checked);
            }}
          />
          <div className="flex h-full items-start p-[16px]">
            <div className="flex w-full">
              <Avatar
                className="ml-auto mt-4 h-10 w-10 self-start"
                style={{ backgroundImage: 'var(--brand-color-gradient)' }}
              >
                {/* {app?.name?.[0]} */}
                {getNextValidChar(app.name, 0)}
              </Avatar>
              <div className="w-full flex-1" style={{ width: '80%', paddingLeft: '10px' }}>
                <Text ellipsis className="app-name mb-1 text-base font-font-weight-600 text-text-5">
                  {app.name}
                </Text>
                <p className="line-clamp-1 text-sm text-text-3">{app.description}</p>
              </div>
            </div>
          </div>
        </div>
      </GradientBox>

      // <div
      //   key={app.id}
      //   className="p-4 border border-gray-200 rounded-lg hover:shadow-md transition-shadow cursor-pointer"
      //   onClick={onClick}
      // >
      //   <div className="text-center font-medium truncate">{app.name}</div>
      // </div>
    );
  },
);

const index: React.FC = () => {
  const { message } = App.useApp();
  const { colorPrimary } = useThemeToken();
  const [searchValue, setSearchValue] = useState('');
  const [extensionData, setExtensionData] = useState<ExtensionPageData[]>([]);

  const [categoryList, setCategoryList] = useState<{ label: string; value: string }[]>([]);
  const [systemList, setSystemList] = useState<{ label: string; value: string }[]>([]);
  const [selectedCategory, setSelectedCategory] = useState('');

  const router = useRouter();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isExtensionLoading, setIsExtensionLoading] = useState(false);

  const [isEditMode, setIsEditMode] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState<boolean>(false);
  const [showConfirmDelete, setShowConfirmDelete] = useState(false);
  const [currentApp, setCurrentApp] = useState<ExtensionInfo | null>(null);
  const pageDataDefault = { page: 1, page_size: 9 };
  const pageSingleDataDefault = { page: 1, page_size: 30 };
  const [selectedTotal, setSelectedTotal] = useState(0);
  const [selectedpage, setSelectedPage] = useState(pageSingleDataDefault?.page);
  const [selectedPageSize, setSelectedPageSize] = useState(pageSingleDataDefault?.page_size);

  const [form] = Form.useForm();
  const [formEdit] = Form.useForm();

  const [name, setName] = useState('');
  const inputCategoryRef = useRef<InputRef>(null);
  const inputSystemRef = useRef<InputRef>(null);

  const [dropdownSystemStyle, setDropdownSystemStyle] = useState({});
  const [dropdownCategoryStyle, setDropdownCategoryStyle] = useState({});

  const { isPc } = useWindowWidth();
  const managePage = useManagePage();
  const [importLoading, setImportLoading] = useState<boolean>(false);

  const [isBatchImportModalVisible, setIsBatchImportModalVisible] = useState(false);

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  const showBatchImportModal = () => {
    setIsBatchImportModalVisible(true);
  };

  const handleOk = () => {
    fetchData();
    setIsBatchImportModalVisible(false);
  };

  const handleCancel = () => {
    setIsBatchImportModalVisible(false);
  };

  const [selectedAppIds, setSelectedAppIds] = useState<string[]>([]);
  const [isAllSelected, setIsAllSelected] = useState(false);

  const handleCheck = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedAppIds([...selectedAppIds, id]);
    } else {
      setSelectedAppIds(selectedAppIds.filter((appId) => appId !== id));
      setIsAllSelected(false);
    }
  };

  const handleSelectAll = () => {
    if (isAllSelected) {
      setSelectedAppIds([]);
    } else {
      const allAppIds = extensionData.flatMap(({ page_data }) =>
        page_data.list.map((app) => app.id),
      );
      setSelectedAppIds(allAppIds);
    }
    setIsAllSelected(!isAllSelected);
  };

  const deleteExtensionBatch = () => {
    setDeleteLoading(true);
    appService
      .extensionBatchDelete({
        ids: selectedAppIds,
        app_id: appId,
      })
      .then((response) => {
        console.log(response.data);
        message?.success('业务删除成功');
        setIsEditMode(false);
        setSelectedAppIds([]);
        setIsAllSelected(false);
        fetchData();
        setShowConfirmDelete(false);
      })
      .catch((error) => {
        console.error('Error:', error);
      })
      .finally(() => {
        setDeleteLoading(false);
      });
  };

  const importMenu = (
    <Menu>
      <Menu.Item
        key="1"
        onClick={() => {
          selectedCategory && form.setFieldsValue({ category: selectedCategory }),
            setIsModalVisible(true);
        }}
      >
        <SvgIcon
          icon="ic--baseline-plus"
          size={30}
          style={{
            padding: '3px',
            marginRight: '10px',
            // color: '#DD80D2',
          }}
        />
        单个创建
      </Menu.Item>
      <Menu.Item
        key="2"
        onClick={() => {
          selectedCategory && form.setFieldsValue({ category: selectedCategory }),
            showBatchImportModal();
        }}
      >
        <SvgIcon
          icon="ic--baseline-playlist-add"
          size={30}
          style={{
            padding: '3px',
            marginRight: '10px',
            // color: '#DD80D2',
          }}
        />
        批量导入
      </Menu.Item>
    </Menu>
  );

  const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
    console.log(current, pageSize);
    setSelectedPage(current);
    setSelectedPageSize(pageSize);
  };

  const handleSystemSearch = (value: string) => {
    if (!value) {
      setDropdownSystemStyle({});
      return;
    }
    const isInList = systemList.some((item) => item.value.includes(value));

    if (!isInList) {
      setDropdownSystemStyle({ display: 'none' });
    } else {
      setDropdownSystemStyle({});
    }
  };

  const handleCategorySearch = (value: string) => {
    if (!value) {
      setDropdownCategoryStyle({});
      return;
    }
    const isInList = categoryList.some((item) => item.value.includes(value));

    if (!isInList) {
      setDropdownCategoryStyle({ display: 'none' });
    } else {
      setDropdownCategoryStyle({});
    }
  };

  const handleSearchChange = useCallback(
    debounce((value: string) => {
      setSearchValue(value);
    }, 300),
    [],
  );

  const handleCategoryChange = (value: string) => {
    setSelectedAppIds([]);
    setIsAllSelected(false);
    setSelectedCategory(value);
    setSelectedPage(pageSingleDataDefault?.page);
    setSelectedPageSize(pageSingleDataDefault?.page_size);
    console.log('选择的分类:', value);
  };

  useEffect(() => {
    fetchExtensionData();
  }, [searchValue, selectedCategory]);

  const handleImport = async (values: any) => {
    console.log(values);
    if (!values?.name.trim()) {
      message.error('业务名称不能为空');
      return;
    }
    if (!values?.web_url?.trim() && !values?.app_url?.trim()) {
      message.error('业务地址不能为空');
      return;
    }
    setImportLoading(true);
    try {
      await appService.extensionCreate({ ...values, app_id: appId });
      fetchData();
      setIsModalVisible(false);
      message.success('导入业务成功');
      form.resetFields();
    } catch (error) {
    } finally {
      setImportLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    console.log(id);
    await appService.extensionDelete(id);
    fetchData();
    setIsDetailModalVisible(false);
    message.success('删除业务成功');
  };

  const handleEdit = async (values: ExtensionInfo) => {
    if (!values?.name.trim()) {
      message.error('业务名称不能为空');
      return;
    }
    if (!values?.web_url && !values?.app_url) {
      message.error('业务地址不能为空');
      return;
    }
    if (currentApp && currentApp?.id) {
      console.log(values, currentApp);
      await appService.extensionUpdate(currentApp?.id, { ...values, app_id: appId });
      // await appService.extensionUpdate(currentApp?.id, {
      //   ...values,
      //   category: currentApp?.category,
      //   system: currentApp?.system,
      // });
      fetchData();
      setIsDetailModalVisible(false);
      message.success('修改业务成功');
    }
  };

  const showDetail = (app: ExtensionInfo) => {
    console.log(app);
    console.log(currentApp);
    setCurrentApp(app);
    setIsDetailModalVisible(true);
  };

  const fetchExtensionData = async (
    pageData: ExtensionpageData = {
      ...(selectedCategory ? pageSingleDataDefault : pageDataDefault),
    },
  ) => {
    try {
      setIsExtensionLoading(true);
      let searchData = {
        ...pageData,
        keywords: searchValue,
        category: selectedCategory,
        app_id: appId,
      };
      if (selectedCategory) {
        searchData = {
          ...searchData,
          page: selectedpage,
          page_size: selectedPageSize,
          app_id: appId,
        };
      }
      const data = await appService.extensionList(searchData);
      console.log(data);
      setExtensionData(data);
      if (selectedCategory) {
        setSelectedTotal(data?.[0]?.page_data?.total || 0);
      }
    } catch (error) {
    } finally {
      setIsExtensionLoading(false);
    }
  };

  useEffect(() => {
    if (!selectedCategory) {
      return;
    }
    setSelectedAppIds([]);
    setIsAllSelected(false);
    fetchExtensionData();
  }, [selectedPageSize, selectedpage]);

  const fetchData = async () => {
    fetchExtensionData();
    appService
      .extensionSystemValueList({
        app_id: appId,
      })
      .then((data) => {
        setSystemList(
          data
            .filter((item: string) => item?.trim())
            .map((item: string) => {
              return {
                value: item,
                label: item,
              };
            }),
        );
      });
    appService
      .extensionCategoryValueList({
        app_id: appId,
      })
      .then((data) => {
        setCategoryList(
          data
            .filter((item: string) => item?.trim())
            .map((item: string) => {
              return {
                value: item,
                label: item,
              };
            }),
        );
      });
  };

  const addCategoryItem = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
    if (!name) {
      message.warning('部门名称不能为空');
      return;
    }
    e.preventDefault();
    setCategoryList([...categoryList, { label: name, value: name }]);
    setName('');
    setTimeout(() => {
      inputCategoryRef.current?.focus();
    }, 0);
  };

  const addSystemItem = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
    if (!name) {
      message.warning('系统名称不能为空');
      return;
    }
    e.preventDefault();
    setSystemList([...systemList, { label: name, value: name }]);
    setName('');
    setTimeout(() => {
      inputSystemRef.current?.focus();
    }, 0);
  };

  const onNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    if (currentApp) {
      formEdit.setFieldsValue(currentApp);
    }
  }, [currentApp, formEdit]);

  return (
    <>
      <Layout className="h-full" style={{ background: '#fff', overflowX: 'hidden' }}>
        <PagesHeader>业务管理</PagesHeader>
        <TipDesc title='维护知识库关联的业务网址信息，可被"应用推荐"使用' className="!my-0 ml-5" />
        <Header style={{ background: '#fff', padding: 0 }}>
          <div className="flex h-full items-center justify-between">
            <div className="flex w-full items-center" style={{ paddingRight: '20px' }}>
              <div
                className="ml-1 flex items-center justify-end gap-4 rounded-lg p-4"
                style={{
                  backgroundColor: '#fff',
                  // borderBottom: '2px solid #EBEDF7',
                  flexDirection: isPc ? 'row' : 'column', // 根据 isPc 决定布局方向
                  alignItems: 'flex-end', // 根据 isPc 决定对齐方式
                }}
              >
                <div className="flex gap-2">
                  <Select
                    value={selectedCategory}
                    options={[{ label: '全部', value: '' }, ...categoryList]}
                    defaultValue="全部"
                    style={{ width: 200 }}
                    showSearch
                    // className="!rounded-button"
                    onChange={handleCategoryChange}
                    className="rg-custom-select"
                    dropdownStyle={{
                      color: 'var(--text-3)',
                    }}
                  />
                  <Input
                    className="rg-custom-input"
                    onChange={(e) => handleSearchChange(e.target.value)}
                    placeholder="搜索"
                    suffix={<SvgIcon icon="work-ic6" size={16} />}
                  />
                </div>
              </div>
              {selectedAppIds.length >= 0 && (
                <div className="ml-auto flex items-center gap-4">
                  {selectedAppIds.length > 0 && (
                    <>
                      {selectedAppIds && <span>已选择{selectedAppIds.length}项</span>}

                      {selectedAppIds.length > 0 && (
                        <Button
                          onClick={() => {
                            setSelectedAppIds([]);
                            setIsEditMode(false);
                            setIsAllSelected(false);
                          }}
                          color="default"
                          variant="outlined"
                          style={{
                            background: 'var(--fill-1)',
                            borderColor: 'var(--line-2)',
                            padding: '0 12px 0px 8px',
                          }}
                          icon={<CloseCircleOutlined />}
                        >
                          取消
                        </Button>
                      )}
                      <Button
                        danger
                        onClick={() => {
                          console.log(selectedAppIds);
                          if (selectedAppIds?.length == 0) {
                            message.info('未选择业务');
                            return;
                          }
                          setShowConfirmDelete(true);
                        }}
                        style={{
                          padding: '0 12px 0px 8px',
                        }}
                      // disabled={tableSelectEdRows.length === 0}
                      >
                        <SvgIcon icon="delete-outlined" size={16} />
                        删除
                      </Button>
                    </>
                  )}

                  <Dropdown overlay={importMenu} trigger={['hover']}>
                    <Button style={{ color: '#1B6DFA', border: '1px solid #1B6DFA' }}>
                      导入业务
                      <DownOutlined />
                    </Button>
                  </Dropdown>
                </div>
              )}
            </div>
          </div>
        </Header>

        {/* 筛选区域 */}
        <Content
          style={{
            background: '#fff',
            border: '1px solid #FFFFFF',
            padding: isPc ? '5px 20px' : '5px',
          }}
          className="flex flex-1 flex-col"
        // className="[-ms-overflow-style:none] [scrollbar-width:none]"
        >
          <div
            className="text-blue-600 inline-flex cursor-pointer items-center"
            onClick={handleSelectAll}
          >
            <Checkbox
              onClick={(e) => {
                e.stopPropagation();
              }}
              onChange={(e) => {
                handleSelectAll();
              }}
              checked={isAllSelected}
            >
              <span className="ml-2 text-sm font-font-weight-400 text-text-5">全选</span>
            </Checkbox>
          </div>

          {/* <Collapse items={items} defaultActiveKey={['1']} onChange={onChange} /> */}

          {isExtensionLoading && <CircleLoading />}

          {!isExtensionLoading && extensionData?.length === 0 && <NotData />}

          {/* {!isExtensionLoading && !extensionData && <Empty />} */}

          {/* 业务列表 */}
          <div className="mt-2" style={{ backgroundColor: '#fff' }}>
            {extensionData.map(({ group_key, page_data }, index) => (
              <div className="rounded-lg pb-2" key={group_key}>
                <div className="flex items-center justify-between">
                  {selectedCategory ? (
                    <Breadcrumb
                      className="custome-separator"
                      separator="/"
                      items={[
                        {
                          title: (
                            <span
                              className="cursor-pointer text-sm font-font-weight-400"
                              onClick={() => {
                                handleCategoryChange('');
                              }}
                            >
                              全部
                            </span>
                          ),
                        },
                        {
                          title: (
                            <span className="text-sm font-font-weight-600 text-text-5">
                              {group_key}
                            </span>
                          ),
                        },
                      ]}
                    />
                  ) : (
                    <div className="flex items-center gap-2">
                      {
                        <Checkbox
                          onChange={(e) => {
                            const isChecked = e.target.checked;
                            const currentGroupAppIds = page_data.list.map((app) => app.id);

                            if (isChecked) {
                              // 选中当前组的所有业务
                              setSelectedAppIds((prevSelectedAppIds) => [
                                ...new Set([...prevSelectedAppIds, ...currentGroupAppIds]),
                              ]);
                            } else {
                              // 取消选中当前组的所有业务
                              setSelectedAppIds((prevSelectedAppIds) =>
                                prevSelectedAppIds.filter((id) => !currentGroupAppIds.includes(id)),
                              );

                              setIsAllSelected(false);
                            }
                          }}
                          checked={page_data.list.every((app) => selectedAppIds.includes(app.id))} // 如果当前组的所有业务都被选中，则复选框为选中状态
                        />
                      }
                      <span className="text-sm font-font-weight-600 text-text-5">{group_key}</span>
                    </div>
                  )}

                  {/* <div className="flex items-center cursor-pointer" onClick={()=>{handleCategoryChange(group_key)}}>
                    <span>查看更多</span>
                    <RightOutlined className="ml-1" />
                  </div> */}
                </div>
                <div className={`grid py-2 ${isPc ? 'grid-cols-5 gap-2' : 'grid-cols-1 gap-2'}`}>
                  {page_data?.list.map((app) => (
                    <AppItem
                      key={app?.id}
                      app={app}
                      onClick={() => showDetail(app)}
                      isPc={isPc}
                      isEditMode={isEditMode}
                      onCheck={handleCheck}
                      selectedAppIds={selectedAppIds}
                    />
                  ))}
                  {!selectedCategory &&
                    page_data?.total > 9 &&
                    page_data?.list?.length == pageDataDefault?.page_size && (
                      <div
                        className="flex w-full cursor-pointer items-center rounded-lg bg-white shadow-sm transition-shadow hover:shadow-md"
                        style={{
                          display: 'flex',
                          justifyContent: 'center',
                          height: '78px',
                          // width: '303px',
                        }}
                        onClick={() => {
                          handleCategoryChange(group_key);
                        }}
                      >
                        {/* <SvgIcon
                          icon="more"
                          size={40}
                          style={{
                            // width: '20%',
                            color: '#a5aac6',
                            maxWidth: '50px',
                            minWidth: '30px',
                          }}
                        /> */}
                        <EllipsisOutlined />
                        <span
                          style={{
                            // width: '70%',
                            paddingLeft: '5px',
                            fontSize: '14px',
                            color: '#6E738C',
                            textAlign: 'left',
                          }}
                        >
                          查看更多
                        </span>
                      </div>
                    )}
                </div>
                {selectedCategory && selectedTotal > pageSingleDataDefault?.page_size && (
                  <div style={{ margin: '20px 10px', display: 'flex', justifyContent: 'end' }}>
                    <Pagination
                      defaultCurrent={selectedpage}
                      defaultPageSize={selectedPageSize}
                      total={selectedTotal}
                      showSizeChanger
                      onChange={onShowSizeChange}
                      pageSizeOptions={[30, 50, 100]}
                    />
                  </div>
                )}
              </div>
            ))}
          </div>
        </Content>
      </Layout>

      {/* 导入业务弹窗 */}
      <Modal
        title="导入业务"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          onFinish={handleImport}
          // labelCol={{ span: 8 }}
          // wrapperCol={{ span: 24 }}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="业务名称"
            rules={[{ required: true, message: '请输入业务名称' }]}
          >
            <Input className="!rounded-button" />
          </Form.Item>
          <Form.Item
            name="name"
            label="业务网址（必须填写其中一项）"
            rules={[{ required: true, message: '请输入业务网址' }]}
          >
            <Form.Item
              name="web_url"
              style={{ marginTop: '16px' }}
              label={
                <div className="flex items-center gap-2">
                  <SvgIcon icon="mingcute--airplay-line" size={20} /> 添加PC端
                </div>
              }
            // rules={[{ required: true, message: '请输入业务网址' }]}
            >
              <Input className="!rounded-button" />
            </Form.Item>
            <Form.Item
              name="app_url"
              style={{ marginBottom: '0px' }}
              label={
                <span className="inset-6 flex items-center gap-2">
                  <SvgIcon icon="mingcute--cellphone-2-line" size={20} /> <span>添加移动端</span>
                </span>
              }
            // rules={[{ required: true, message: '请输入业务网址' }]}
            >
              <Input className="!rounded-button" />
            </Form.Item>
          </Form.Item>

          <Form.Item
            name="category"
            label="所属部门"
            rules={[{ required: true, message: '请选择或输入部门' }]}
          >
            <Select
              showSearch
              allowClear
              placeholder="请选择或输入部门"
              onBlur={(e) => {
                e.target?.value && form.setFieldValue('category', e.target?.value);
              }}
              options={categoryList}
              onSearch={handleCategorySearch}
              dropdownStyle={dropdownCategoryStyle}
            />
            {/* <Select options={categoryList} /> */}
            {/* <Select
              placeholder="请选择所属部门"
              showSearch
              dropdownRender={(menu) => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space style={{ padding: '0 8px 4px' }}>
                    <Input
                      placeholder="输入新部门"
                      ref={inputCategoryRef}
                      value={name}
                      onChange={onNameChange}
                      onKeyDown={(e) => e.stopPropagation()}
                    />
                    <Button type="text" icon={<PlusOutlined />} onClick={addCategoryItem}>
                      添加部门
                    </Button>
                  </Space>
                </>
              )}
              options={categoryList}
            /> */}
          </Form.Item>

          <Form.Item
            name="system"
            label="所属系统"
            rules={[{ required: true, message: '请选择或输入系统' }]}
          >
            <Select
              showSearch
              allowClear
              placeholder="请选择或输入系统"
              onBlur={(e) => {
                e.target?.value && form.setFieldValue('system', e.target?.value);
              }}
              options={systemList}
              onSearch={handleSystemSearch}
              dropdownStyle={dropdownSystemStyle}
            />
            {/* <Select options={systemList} /> */}
            {/* <Select
              placeholder="请选择所属系统"
              showSearch
              dropdownRender={(menu) => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space style={{ padding: '0 8px 4px' }}>
                    <Input
                      placeholder="输入新系统"
                      ref={inputSystemRef}
                      value={name}
                      onChange={onNameChange}
                      onKeyDown={(e) => e.stopPropagation()}
                    />
                    <Button type="text" icon={<PlusOutlined />} onClick={addSystemItem}>
                      添加系统
                    </Button>
                  </Space>
                </>
              )}
              options={systemList}
            /> */}
          </Form.Item>
          <Form.Item
            name="description"
            label="业务介绍"
            rules={[{ required: true, message: '请输入业务介绍' }]}
          >
            <Input.TextArea rows={4} className="!rounded-button" />
          </Form.Item>
          <Form.Item className="mb-0 text-right">
            <Space>
              <Button
                onClick={() => {
                  setIsModalVisible(false);
                }}
                className="!rounded-button"
              >
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                className="!rounded-button"
                loading={importLoading}
              >
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 业务详情弹窗 */}
      <Modal
        title="业务详情"
        open={isDetailModalVisible}
        onCancel={() => {
          setIsDetailModalVisible(false);
          // setCurrentApp(null)
          // formEdit.resetFields();
        }}
        footer={null}
        key={currentApp?.id}
      >
        {currentApp && (
          <Form
            key={currentApp?.id}
            // key={currentApp?.toString()}
            // preserve={false}
            form={formEdit}
            // onValuesChange={()=>{console.log('aaaa')}}
            initialValues={currentApp}
            onFinish={handleEdit}
            layout="vertical"
          >
            <Form.Item
              name="name"
              label="业务名称"
              rules={[{ required: true, message: '请输入业务名称' }]}
            >
              <Input className="!rounded-button" />
            </Form.Item>
            {/* <Form.Item name="web_url" label="业务网址（PC端）">
              <Input className="!rounded-button" />
            </Form.Item>
            <Form.Item name="app_url" label="业务网址（移动端）">
              <Input className="!rounded-button" />
            </Form.Item> */}
            <Form.Item
              name="name"
              label="业务网址（必须填写其中一项）"
              rules={[{ required: true, message: '请输入业务网址' }]}
            >
              <Form.Item
                name="web_url"
                style={{ marginTop: '16px' }}
                label={
                  <div className="flex items-center gap-2">
                    <SvgIcon icon="mingcute--airplay-line" size={20} /> 添加PC端
                  </div>
                }
              // rules={[{ required: true, message: '请输入业务网址' }]}
              >
                <Input className="!rounded-button" />
              </Form.Item>
              <Form.Item
                name="app_url"
                style={{ marginBottom: '0px' }}
                label={
                  <span className="inset-6 flex items-center gap-2">
                    <SvgIcon icon="mingcute--cellphone-2-line" size={20} /> <span>添加移动端</span>
                  </span>
                }
              // rules={[{ required: true, message: '请输入业务网址' }]}
              >
                <Input className="!rounded-button" />
              </Form.Item>
            </Form.Item>
            <Form.Item
              name="category"
              label="所属部门"
              rules={[{ required: true, message: '请选择或输入部门' }]}
            >
              <Select
                className="!rounded-button"
                showSearch
                allowClear
                options={categoryList}
                placeholder="请选择部门"
                onChange={(value) => {
                  console.log(value);
                  value && formEdit.setFieldValue('category', e.target?.value);
                  // && setCurrentApp((pre) => ({ ...pre, category: value }));
                }}
                onBlur={(e) => {
                  console.log(e.target?.value);
                  e.target?.value && formEdit.setFieldValue('category', e.target?.value);
                  // && setCurrentApp((pre) => ({ ...pre, category: e.target?.value }));
                }}
                onSearch={handleCategorySearch}
                dropdownStyle={dropdownCategoryStyle}
              />
            </Form.Item>
            <Form.Item
              name="system"
              label="所属系统"
              rules={[{ required: true, message: '请选择或输入系统' }]}
            >
              <Select
                className="!rounded-button"
                showSearch
                allowClear
                placeholder="请选择系统"
                options={systemList}
                onChange={(value) => {
                  value && formEdit.setFieldValue('system', value);
                  // && setCurrentApp((pre) => ({ ...pre, system: value }));
                }}
                onBlur={(e) => {
                  e.target?.value && formEdit.setFieldValue('system', e.target?.value);
                  // && setCurrentApp((pre) => ({ ...pre, system: e.target?.value }));
                }}
                onSearch={handleSystemSearch}
                dropdownStyle={dropdownSystemStyle}
              />
            </Form.Item>
            <Form.Item
              name="description"
              label="业务介绍"
              rules={[{ required: true, message: '请输入业务介绍' }]}
            >
              <Input.TextArea rows={4} className="!rounded-button" />
            </Form.Item>
            <Form.Item className="mb-0 text-right">
              <Space>
                <Popconfirm
                  title="确定要删除该业务吗？"
                  onConfirm={() => handleDelete(currentApp.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button danger className="!rounded-button">
                    删除
                  </Button>
                </Popconfirm>
                <Button type="primary" htmlType="submit" className="!rounded-button">
                  修改
                </Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>
      <BatchImportModal
        visible={isBatchImportModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      />
      <DeleteConfirmModal
        visible={showConfirmDelete}
        text={
          <span
            dangerouslySetInnerHTML={{
              __html: `确认删除选中的 <strong>${selectedAppIds?.length} 个业务</strong> 吗？`,
            }}
          />
        }
        loading={deleteLoading}
        onCancel={() => setShowConfirmDelete(false)}
        onConfirm={() => deleteExtensionBatch()}
      />
    </>
  );
};

export default index;
